package com.sk.weichat.ui.message;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.adapter.MessageCallAdapter;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.User;
import com.sk.weichat.broadcast.MsgBroadcast;

import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.GroupMessageDao;

import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.util.ToastUtil;

import com.sk.weichat.view.SelectionFrame;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;

/**
 * 打招呼消息
 * create by swy 2019-07-03
 */
public class MessageCallActivity extends BaseActivity implements View.OnClickListener {

    private RecyclerView mMainRecyclerView;
    private SmartRefreshLayout mRefreshLayout;
    private String mLoginUserId;
    private ArrayList<Friend> mUnReplyList;
    private ArrayList<User> mUserList;
    private MessageCallAdapter mMainAdapter;
    private TextView mTvNumLeft;
    private int mPage = 1;
    private TextView mTvTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_call);
        initActionBar();
        initView();

    }

    @Override
    protected void onResume() {
        super.onResume();
        loadDate();
    }

    public int getNumTotal() {
        int numMessage = FriendDao.getInstance().getMsgUnReadNumTotal(coreManager.getSelf().getUserId());
        Friend newFriend = FriendDao.getInstance().getFriend(coreManager.getSelf().getUserId(), Friend.ID_NEW_FRIEND_MESSAGE);//关系通知未读数
        int unReadNumTotal = GroupMessageDao.getInstance().getGroupMsgUnReadNumTotal(coreManager.getSelf().getUserId());
        numMessage += newFriend.getUnReadNum()+unReadNumTotal;
        return numMessage;
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.mergerStatus).setBackgroundColor(ContextCompat.getColor(this, R.color.white));

        mTvNumLeft = (TextView) findViewById(R.id.tv_num_left);
        updateNumLeft();

        mTvTitle = (TextView) findViewById(R.id.tv_title_center);
        mTvTitle.setText(R.string.message_call_title);
        ImageView imgRight = (ImageView) findViewById(R.id.iv_title_right);
        imgRight.setImageResource(R.drawable.icon_clear_big);
        imgRight.setOnClickListener(this);
        findViewById(R.id.iv_title_left).setOnClickListener(this);
    }

    private void updateNumLeft() {
        int numTotal = getNumTotal();
        if (numTotal < 1) {
            mTvNumLeft.setVisibility(View.GONE);
        } else if (numTotal > 99) {
            mTvNumLeft.setVisibility(View.VISIBLE);
            mTvNumLeft.setText("99+");
        } else {
            mTvNumLeft.setVisibility(View.VISIBLE);
            mTvNumLeft.setText(numTotal + "");
        }
    }

    private void initView() {

        mLoginUserId = coreManager.getSelf().getUserId();
        mUnReplyList = new ArrayList<>();//未回复
        mUserList = new ArrayList<>();
        initRefreshLayout();
        initRecyclerView();

    }

    private void initRefreshLayout() {
        mRefreshLayout = findViewById(R.id.refresh_layout_msg_call);
        mRefreshLayout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        mRefreshLayout.setEnableOverScrollBounce(false);//禁止越界回弹
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPage = 1;
                loadDate();
            }
        });

        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadDate();
            }
        });
    }

    private void initRecyclerView() {

        mMainRecyclerView = findViewById(R.id.recycler_msg_call);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mMainRecyclerView.setLayoutManager(manager);
        mMainAdapter = new MessageCallAdapter(mUnReplyList, mUserList);
        mMainRecyclerView.setAdapter(mMainAdapter);
        mMainAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent;
                switch (view.getId()) {

                    case R.id.layout_call_list_item://点击item
                        intent = new Intent(MessageCallActivity.this, ChatActivity.class);
                        intent.putExtra(ChatActivity.FRIEND, mUnReplyList.get(position));
                        startActivity(intent);
                        clearMessageNum(mUnReplyList.get(position));
                        break;

                    case R.id.img_call_avatar://点击头像
                        intent = new Intent(MessageCallActivity.this, PersonalCenterActivity.class);
                        intent.putExtra(AppConstant.EXTRA_USER_ID, mUnReplyList.get(position).getUserId());
                        startActivity(intent);
                        break;

                }
            }
        });
    }

    private void clearAllMessageNum(List<Friend> friendList) {

        for (Friend friend : friendList) {
            friend.setUnReadNum(0);
            FriendDao.getInstance().markUserMessageRead(mLoginUserId, friend.getUserId());
        }
        mMainAdapter.notifyDataSetChanged();
        updateNumLeft();
        MsgBroadcast.broadcastMsgUiUpdate(mContext);
    }

    private void clearMessageNum(Friend friend) {
        friend.setUnReadNum(0);
        FriendDao.getInstance().markUserMessageRead(mLoginUserId, friend.getUserId());

        for (int i = 0; i < mUnReplyList.size(); i++) {
            if (Objects.equals(mUnReplyList.get(i).getUserId(), friend.getUserId())) {
                mMainAdapter.notifyItemChanged(i);
            }
        }

        int UnReadNumCount = 0;
        for (Friend replayFriend : mUnReplyList) {
            UnReadNumCount += replayFriend.getUnReadNum();
        }
        if (UnReadNumCount == 0) {
            mTvTitle.setText(getResources().getString(R.string.message_call_title));
        } else {
            mTvTitle.setText(getResources().getString(R.string.message_call_title) + "(" + UnReadNumCount + ")");
        }


        updateNumLeft();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;

            case R.id.iv_title_right:
                showClearUnReadDialog();
                break;
        }
    }

    /**
     * 清除未读消息弹框
     */
    private void showClearUnReadDialog() {

        SelectionFrame mSF = new SelectionFrame(this);
        mSF.setSomething(getString(R.string.dialog_title), getString(R.string.msg_clear_unread), new SelectionFrame.OnSelectionFrameClickListener() {
            @Override
            public void cancelClick() {

            }

            @Override
            public void confirmClick() {
                clearAllMessageNum(mUnReplyList);
            }
        });
        mSF.show();
    }


    private void loadDate() {
        mUnReplyList.clear();
        List<Friend> friendList = FriendDao.getInstance().getNearlyFriendMsg(mLoginUserId);
        List<Friend> unReplayFriendList = new ArrayList<>();
        if (friendList.size() > 0) {
            for (int i = 0; i < friendList.size(); i++) {
                Friend friend = friendList.get(i);
                if (friend != null && friend.getStatus() != 8 //非客服
                        && !friend.getUserId().equals(Friend.ID_NEW_FRIEND_MESSAGE)//非系统消息
                        && friend.getStatus() != Friend.STATUS_FRIEND //非好友
                        && friend.getIsBeBlack() != 1 //没有被拉黑
                        && friend.getReplyStatus() == Friend.STATUS_REPLAY_SINGLE) {//未回复

                    unReplayFriendList.add(friend);
                }
            }
            if (unReplayFriendList.size() > 0) {
                loadUserList(unReplayFriendList);
            } else {
                finish();
            }

        } else {
            finish();
        }

    }

    private void loadUserList(List<Friend> unReplayFriendList) {

        String userIds = "";
        for (Friend friend : unReplayFriendList) {
            userIds += friend.getUserId() + ",";
        }
        if (userIds.length() > 1) {
            userIds = userIds.substring(0, userIds.length() - 1);
        }
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("userIds", userIds);

        HttpUtils.get().url(coreManager.getConfig().USERLIST_GET_URL)
                .params(params)
                .build()
                .execute(new BaseCallback<User[]>(User[].class) {

                    @Override
                    public void onResponse(ObjectResult<User[]> result) {

                        if (Result.checkSuccess(mContext, result)) {
                            if (mPage == 1) {
                                mRefreshLayout.finishRefresh();
                                mUserList.clear();
                            } else {
                                mRefreshLayout.finishLoadMore();
                            }
                            User[] users = result.getData();
                            for (int i = 0; i < users.length; i++) {
                                if (TextUtils.isEmpty(users[i].getUserId())) {//去掉异常账号
                                    FriendDao.getInstance().deleteFriend(unReplayFriendList.get(i).getOwnerId(), unReplayFriendList.get(i).getUserId());
                                    unReplayFriendList.remove(i);

                                } else {
                                    mUserList.add(users[i]);
                                }

                            }
                            mUnReplyList.addAll(unReplayFriendList);
                            mMainAdapter.notifyDataSetChanged();
                            int UnReadNumCount = 0;
                            for (Friend friend : mUnReplyList) {
                                UnReadNumCount += friend.getUnReadNum();
                            }
                            if (UnReadNumCount == 0) {
                                mTvTitle.setText(getResources().getString(R.string.message_call_title));
                            } else {
                                mTvTitle.setText(getResources().getString(R.string.message_call_title) + "(" + UnReadNumCount + ")");
                            }

                            mPage++;
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtil.showNetError(mContext);
                    }
                });
    }

}
